<?php


namespace app\app\controller;


use app\common\model\RecommendVod;
use QL\QueryList;
use think\Log;

class Category extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $list = [
            [
                'name' => "推荐",
                "isCate" => false,
                "cateId" => 0
            ],
            [
                'name' => "电视剧",
                "isCate" => true,
                "cateId" => 2
            ],
            [
                'name' => "电影",
                "isCate" => true,
                "cateId" => 1
            ],
//                [
//                    'name' => "欧美剧",
//                    "isCate" => true,
//                    "cateId" => 16
//                ],
//                [
//                    'name' => "日韩剧",
//                    "isCate" => true,
//                    "cateId" => 15
//                ],
//                [
//                    'name' => "港台剧",
//                    "isCate" => true,
//                    "cateId" => 14
//                ],
//                [
//                    'name' => "国产剧",
//                    "isCate" => true,
//                    "cateId" => 13
//                ],
            [
                'name' => "综艺",
                "isCate" => true,
                "cateId" => 3
            ],
            [
                'name' => "动漫",
                "isCate" => true,
                "cateId" => 4
            ],

        ];
        $this->success('获取成功！', $list);
    }

    public function extendsInfo()
    {
        $catId = input('catId', 0, 'intval');
        if ($catId < 1) {
            $this->error('获取失败！');
        }
        $extendsInfo = getTypeExtend($catId);
//            dump($extendsInfo);
        $this->success('获取成功！', $extendsInfo);
    }

    public function getDataBaseExtendsInfo()
    {
        $typeIds = db('type')->where('type_mid', 1)->column('type_name', 'type_id');
        foreach ($typeIds as $id => $name) {
            $vodClasses = db('vod')->where(['type_id|type_id_1' => $id])->field('vod_class')->column('vod_class');
//            dump($vodClasses);
            $vodClassArray = [];
            foreach ($vodClasses as $vodClass) {
                $data = explode(',', $vodClass);
                foreach ($data as $item) {
                    if (isset($vodClassArray[$item])) {
                        $vodClassArray[$item] += 1;
                    } else {
                        $vodClassArray[$item] = 1;
                    }
                }
            }
            asort($vodClassArray);
            $vodClassArray = array_keys(array_reverse($vodClassArray));
            echo '当前分类' . $name . "的扩展分类为<br/>" . implode(',', $vodClassArray) . "<br/>";
        }
    }

    public function getCrawlData()
    {
        $list = file_get_contents(ROOT_PATH . 'tuijian.json');
        $list = json_decode($list, true);
        return json($list);
    }

    public function dealDoubanMovie()
    {
        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Headers: *');
        if (!request()->isPost()) {
            $this->error('请求失败！');
        }
//            $type = input('type');
//            dump($input['type']);
//            dump($input['leixing']);
        $input = input();
        $timeStart = microtime(true);
        $tuijianJsonPath = ROOT_PATH . "tuijian.json";
//            $content = json_encode(input());
//            file_put_contents(ROOT_PATH.'douban_'.microtime(true),$content);
        $list = file_get_contents($tuijianJsonPath);
        $list = json_decode($list, true);

        if (!isset($input['leixing'])) {
            $this->error('频道有错误！');
        }

        if (!isset($input['type'])) {
            $this->error('类型有错误！');
        }
        if (!isset($list[$input['leixing']])) {
            $this->error('没有该频道');
        }
        if (!isset($list[$input['leixing']][$input['type']])) {
            $this->error('没有该类型');
        }
        $ids = [];
        if (!empty($input['list'])) {
            //创建文件锁
            $lockFilePath = ROOT_PATH . 'dealDoubanMovie_lock';
            //重要的事情检查三遍 防止极端情况发生
            if (file_exists($lockFilePath)) {
                $this->error('进程正在处理中,请5s后再处理数据！');
            }
            if (file_exists($lockFilePath)) {
                $this->error('进程正在处理中,请5s后再处理数据！');
            }
            if (file_exists($lockFilePath)) {
                $this->error('进程正在处理中,请5s后再处理数据！');
            }
            file_put_contents($lockFilePath, '1');

            $failedItems = [];
            $count = count($input['list']);
            foreach ($input['list'] as $item) {
                //查询数据
                $vodInfo = db('vod')->where('vod_name', $item['name'])->where('vod_status', 1)->find();
                if (empty($vodInfo)) {
                    $failedItems[] = $item;
                    continue;
                }
                $ids[] = $vodInfo['vod_id'];
                db('vod')->where('vod_id', $vodInfo['vod_id'])->update(
                    [
                        'vod_douban_score' => $item['fen'],
                        'vod_score' => $item['fen'],
                        'vod_douban_id' => $item['id'],
                        'vod_pic' => (empty($vodInfo['vod_pic']) || strpos(
                                $vodInfo['vod_pic'],
                                '/upload/'
                            ) === 0) ? $item['pic'] : $vodInfo['vod_pic']
                    ]
                );
            }

            $timeEnd = microtime(true);
            $time = $timeEnd - $timeStart;
            $message = $input['leixing'] . '_' . $input['type'] . ' 数据处理共计用时' . $time . '秒,' . "\n" . '共计处理数据' . $count . '条,' . "\n" . '失败数据' . count(
                    $failedItems
                ) . '条';
            if (!empty($failedItems)) {
                $fileName = ROOT_PATH . 'json/faildjson_' . $input['leixing'] . '_' . $input['type'] . '.json';
                file_put_contents($fileName, json_encode($failedItems, JSON_UNESCAPED_UNICODE), 0);
                $message .= "\n" . '失败数据保存在' . $fileName;
            }
            $list[$input['leixing']][$input['type']]['ids'] = $ids;
            $list[$input['leixing']][$input['type']]['url'] = $input['url'];
//                dump($message);
//                sendDingding($message);
//                dump($list);
            file_put_contents($tuijianJsonPath, json_encode($list, JSON_UNESCAPED_UNICODE));
            unlink($lockFilePath);//解除文件锁
//                exit;
            $this->success('处理结束!');
        }

        $this->error('数据接收了，但是并没有被很好的处理！');
    }

    public function crawleData()
    {
        $urls = [
            "最新电视剧" => 'http://www.qnvod.net/top/guochan.html',
            "最新电影" => "http://www.qnvod.net/top/dianying.html",
            "人气欧美剧" => "http://www.qnvod.net/top/oumei.html",
            "人气日韩剧" => "http://www.qnvod.net/top/rihan.html",
            "人气港台剧" => "http://www.qnvod.net/top/gangtai.html",
            "热门动漫" => "http://www.qnvod.net/top/donghua.html"
        ];
        $lanmuIds = [
            "最新电视剧" => 2,
            "最新电影" => 3,
            "人气欧美剧" => 5,
            "人气日韩剧" => 6,
            "人气港台剧" => 7,
            "热门动漫" => 8
        ];
        $cateIds = [
            "最新电视剧" => 2,
            "最新电影" => 1,
            "人气欧美剧" => 16,
            "人气日韩剧" => 15,
            "人气港台剧" => 14,
            "热门动漫" => 4
        ];
        $tuijianJsonPath = ROOT_PATH . "tuijian.json";
//            $content = json_encode(input());
//            file_put_contents(ROOT_PATH.'douban_'.microtime(true),$content);
        $list = file_get_contents($tuijianJsonPath);
        $list = json_decode($list, true);
        $timeAdded = time();
        foreach ($urls as $type => $url) {
            $timeStart = microtime(true);
            if (!isset($list['推荐'][$type])) {
                $this->error('没有该类型');
            }
            //查询数据库得到分类ID
            $ids = [];
            $recommends = [];
            $failedItems = [];
            $titles = QueryList::get($url)->rules(
                [
                    'title' => ['a', 'title']
                ]
            )->range('.top500 ul li')->queryData();
            $count = count($titles);
            foreach ($titles as $title) {
                if ($title['title'] == '琉璃美人煞') {
                    $title['title'] = '琉璃';
                }
                $where = [];
                if (isset($cateIds[$type])) {
                    $where['type_id|type_id_1'] = $cateIds[$type];
                }
                //查询数据
                $vodInfo = db('vod')->where($where)->where('vod_name', $title['title'])->where('vod_status', 1)->order('vod_id', 'asc')->find();
                if (empty($vodInfo)) {
                    $failedItems[] = $title['title'];
                    continue;
                }
                $ids[] = $vodInfo['vod_id'];

            }
            $existIds = db('recommend_vod')->where('recommend_id', $lanmuIds[$type])->column('vod_id', 'id');
//                dump('查询到的数据');
//                dump($existIds);
            //处理差集
            $deletedIds = array_diff($existIds, $ids);
            dump('要删除的数据 xxxx');
            //要删除的数据
            dump(count($deletedIds));
            if (!empty($deletedIds)) {
                db('recommend_vod')->where('recommend_id', $lanmuIds[$type])->whereIn('vod_id', $deletedIds)->where('sort_manual', 999)->delete();
            }
            $insertIds = array_diff($ids, $existIds);
            dump('要插入的数据 xxxx');
            //要更新的数据
            dump(count($insertIds));
//                $needUpdate = array_intersect($existIds,$ids);
//                dump('需要更新的数据');
//                dump($needUpdate);
            $updateData = [];
            $insertData = [];
            foreach ($ids as $key => $val) {
                if (in_array($val, $insertIds)) {
                    $insertData[] = [
                        'recommend_id' => $lanmuIds[$type],
                        'vod_id' => $val,
                        'sort' => $key + 1,
                        'time_added' => $timeAdded
                    ];
                } else {
                    $updateData[] = [
                        'recommend_id' => $lanmuIds[$type],
                        'vod_id' => $val,
                        'sort' => $key + 1,
                        'time_added' => $timeAdded,
                        'id' => array_search($val, $existIds)
                    ];
                }
            }
            $updateData = array_merge($updateData, $insertData);
            dump(' 更新插入总数据量为 ' . count($updateData));
            //批量更新和插入
            $updateSql = (new RecommendVod())->saveAll($updateData);
            //处理交集
//                db('recommend_vod')->insertAll($recommends);
            $timeEnd = microtime(true);
            $time = $timeEnd - $timeStart;
            $message = '推荐' . '_' . $type . ' 数据处理共计用时' . $time . '秒,' . "\n" . '共计处理数据' . $count . '条,' . "\n" . '失败数据' . count(
                    $failedItems
                ) . '条';
            if (!empty($failedItems)) {
                $fileName = ROOT_PATH . 'json/faildjson_' . '推荐' . '_' . $type . '.json';
                file_put_contents($fileName, json_encode($failedItems, JSON_UNESCAPED_UNICODE), 0);
                $message .= "\n" . '失败数据保存在' . $fileName;
            }
            $list['推荐'][$type]['ids'] = $ids;
            $list['推荐'][$type]['url'] = $url;
//                dump($message);
            sendDingding($message, '推荐更新');
//                dump($list);
            file_put_contents($tuijianJsonPath, json_encode($list, JSON_UNESCAPED_UNICODE));
//                exit;

        }
//            $this->success('处理结束!');
        return redirect(url('index/rebuildCache'));

    }

}